package com.edu.robot.modules.robot.controller;

import com.edu.robot.model.R;
import com.edu.robot.model.enums.ResultCodeEnum;
import com.edu.robot.model.error.BizException;
import com.edu.robot.modules.robot.controller.vo.PageQuery;
import com.edu.robot.modules.robot.controller.vo.ToolVO;
import com.edu.robot.modules.robot.dto.ParameterDTO;
import com.edu.robot.modules.robot.service.CrToolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-03-23 12:00
 **/

@RestController
@RequestMapping("/robot/tool")
public class ToolController {

	@Autowired
	private CrToolService crToolService;

	@PostMapping("/add")
	public R<?> addTool(@RequestBody @Validated ToolVO toolVO) {
		return crToolService.addTool(toolVO);
	}

	/*
	* @author 范铁凝
	* @date 2025/4/12
	* 编辑工具
	*/
	@PostMapping("/edit")
	public R<?> editTool(@RequestBody @Validated ToolVO toolVO) {
		return crToolService.editTool(toolVO);
	}

	/*
	* @author 范铁凝
	* @date 2025/4/12
	* 删除工具
	*/
	@PostMapping("/delete/{id}")
	public R<?> deleteTool(@PathVariable("id") String id) {
		return crToolService.deleteTool(id);
	}

	/*
	* @author 范铁凝
	* @date 2025/4/12
	* 调用工具
	*/
	@PostMapping("/use")
	public R<?> useTool(@RequestBody @Validated ToolVO toolVO) {
		List<ParameterDTO> parameters = toolVO.getParameters();

		//获取参数，转成key-value
		Map<String, Object> params = new HashMap<>();
		parameters.forEach(
				parameterDTO -> {

					if (!parameterDTO.isRequired()){
						return;
					}
					if (parameterDTO.getDefaultValue() == null){
						throw new BizException(ResultCodeEnum.PARAM_INVALID, "参数" + parameterDTO.getName() + "不能为空");
					}
					params.put(parameterDTO.getName(), parameterDTO.getDefaultValue());
				}
		);
		String res = crToolService.useTool(toolVO.getId(), params);

		return R.success(res);
	}

	/*
	* @author 范铁凝
	* @date 2025/4/12
	* 分页查询工具
	*/
	@PostMapping("/list")
	public R<?> getToolList(@RequestBody @Validated PageQuery<ToolVO> query) {
		return R.success(crToolService.listTool(query));
	}
}
